let module = function () {
  //模块容器
  const collections = {}
  //利用函数套函数方式实现闭包
  return function (name, modules, action) {
    modules = modules.map((m) => collections[m])
    collections[name] = action.call(null, ...modules)
    // console.log(collections)
  }
}.call()

module('Util', [], function () {
  return {
    sum(data, field) {
      return data.reduce((a, b) => a + b[field], 0)
    },
    avg() {
      console.log('@avg method')
    },
    order(data, field, type = 'asc') {
      return data.sort((a, b) => {
        return type == 'asc' ? a[field] - b[field] : b[field] - a[field]
      })
    },
    remove(data, field) {
      data.splice(m, 1)
      return data
    },
  }
})

// 声明购物类
class Cart {
  constructor(goods) {
    this.goods = goods
  }

  total() {
    let total
    module('Cart', ['Util'], (Util) => {
      total = Util.sum(this.goods, 'price')
    })
    // total = require(['Util'], (Util) => {
    //   total = Util.sum(this.goods, 'price')
    // })
    return total
  }
  order(field = 'price', type = 'asc') {
    let goods = []
    module('Cart', ['Util'], (Util) => {
      goods = Util.order(this.goods, field, type)
    })
    return goods
  }
  remove(field = 'sn') {
    let num = indexOf
  }
}

const goods = [
  { sn: 1, name: 'Ipad', price: 3800 },
  { sn: 2, name: 'MacBook Air', price: 7800 },
  { sn: 3, name: 'MacBook Pro', price: 13800 },
  { sn: 4, name: 'MacBook M1', price: 15800 },
  { sn: 5, name: 'IWatch', price: 2800 },
]

let cart = new Cart(goods)
console.log(cart.total())
console.table(cart.order('price', 'desc'))
